package com.rocketsoftware.rdop.controller;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.google.common.collect.Lists;
//import com.google.common.collect.Maps;
//import com.rocketsoftware.common.util.ResultBean;
//import com.rocketsoftware.rdop.config.quartz.QuartzBean;
//import com.rocketsoftware.rdop.dao.rdop.model.JobQueue;
//import com.rocketsoftware.rdop.scheduler.AbsJob;
//import com.rocketsoftware.rdop.scheduler.JobContextImpl;
//import com.rocketsoftware.rdop.scheduler.JobFactory;
//import com.rocketsoftware.rdop.service.job.JobQueueService;
//import com.rocketsoftware.rdop.service.job.JobService;
//import com.rocketsoftware.rdop.service.job.SchedulerService;
//import com.rocketsoftware.rdop.service.job.TestJob;
//import org.quartz.*;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.*;

//@RestController
//@RequestMapping("tests")
public class JobController {
//    private final static Logger LOGGER = LoggerFactory.getLogger(JobController.class);
//
//    private final String baseuri = "/job";
//
//    @Autowired
//    @Qualifier("Scheduler")
//    private Scheduler scheduler;
//
//    @Autowired
//    private JobService jobService;
//    @Autowired
//    private SchedulerService schedulerService;
//    @Autowired
//    private ObjectMapper objectMapper;
//
//    @Autowired
//    private JobQueueService jobQueueService;
//
//    /**
//     * 新增任务
//     *
//     * @param quartz
//     * @return
//     */
//    @RequestMapping(value = baseuri + "/addschedule")
//    public ResultBean<String> save(QuartzBean quartz) throws Exception {
//        LOGGER.info("新增任务");
//        int i = 100 / 0;
//        if (quartz.getOldJobGroup() != null) {
//            JobKey key = new JobKey(quartz.getOldJobName(), quartz.getOldJobGroup());
//            scheduler.deleteJob(key);
//        }
//        //获取.class
//        Class cls = Class.forName(quartz.getJobClassName());
//        cls.newInstance();
//        //创建jobdetail
//        JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(), quartz.getJobGroup())
//                //设置参数
//                //.usingJobData("aa", "ceshi")
//                //描述
//                .withDescription(quartz.getDescription()).build();
//        // 使用cron表达式
//        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder
//                .cronSchedule(quartz.getCronExpression());
//        Trigger trigger = TriggerBuilder.newTrigger()
//                .withIdentity("trigger" + quartz.getJobName(), quartz.getJobGroup()).startNow()
//                .withSchedule(cronScheduleBuilder).build();
//        //交由Scheduler安排触发
//        scheduler.scheduleJob(job, trigger);
//        return ResultBean.success("OK");
//    }
//
//    /**
//     * 获取任务列表
//     *
//     * @param name
//     * @return
//     */
//    @RequestMapping(value = baseuri + "/list")
//    public ResultBean<Object> list(String name) {
//        LOGGER.info("任务列表");
//        List<QuartzBean> list = jobService.listQuartzBean(name);
//        return ResultBean.success(list);
//    }
//
//    /**
//     * 立即执行
//     *
//     * @param quartz
//     * @return
//     */
//    @RequestMapping(value = baseuri + "/run")
//    public ResultBean<String> trigger(QuartzBean quartz) throws Exception {
//        LOGGER.info("立即执行");
//        JobKey key = new JobKey("job1", "group1");
//        scheduler.triggerJob(key);
//        return ResultBean.success(key + " invoked.");
//    }
//
//    /**
//     * 暂停任务
//     *
//     * @param quartz
//     * @return
//     */
//    @RequestMapping(value = baseuri + "/pause")
//    public ResultBean<String> pause(QuartzBean quartz) throws Exception {
//        LOGGER.info("暂停任务");
//        JobKey key = new JobKey("job1", "group1");
//        scheduler.pauseJob(key);
//        return ResultBean.success(key + " paused.");
//    }
//
//    /**
//     * 从暂停中恢复过来
//     *
//     * @param quartz
//     * @return
//     */
//    @RequestMapping(value = baseuri + "/resume")
//    public ResultBean<String> resume(QuartzBean quartz) throws Exception {
//        LOGGER.info("恢复任务");
//        JobKey key = new JobKey("job1", "group1");
//        scheduler.resumeJob(key);
//        return ResultBean.success(key + " resumed");
//    }
//
//    /**
//     * 删除任务
//     *
//     * @param quartz
//     * @return
//     */
//    @RequestMapping(value = baseuri + "/delete")
//    public ResultBean<String> remove(QuartzBean quartz) throws Exception {
//        LOGGER.info("删除任务");
//        TriggerKey triggerKey = TriggerKey.triggerKey("trigger1", "group1");
//        // 停止触发器
//        scheduler.pauseTrigger(triggerKey);
//        // 移除触发器
//        scheduler.unscheduleJob(triggerKey);
//        // 删除任务
//        scheduler.deleteJob(JobKey.jobKey("job1", "group1"));
//        return ResultBean.success(triggerKey + " deleted");
//    }
//
//    @RequestMapping(value = baseuri + "/add")
//    public ResultBean<String>  addTestJob(Boolean force) throws SchedulerException {
//        String cronExpression = "0/5 * * * * ?";
//        JobKey jobKey = JobKey.jobKey("job1", "group1");
//        TriggerKey triggerKey = TriggerKey.triggerKey("trigger1", "group1");
//        if(scheduler.checkExists(triggerKey) && force == Boolean.TRUE) {
//            // 停止触发器
//            scheduler.pauseTrigger(triggerKey);
//            // 移除触发器
//            scheduler.unscheduleJob(triggerKey);
//
//            scheduler.deleteJob(jobKey);
//        } else {
//           return ResultBean.success(jobKey + " is existed.");
//        }
//
//        // define the job and tie it to our HelloJob class
//        JobDetail job = JobBuilder.newJob(TestJob.class).withIdentity(jobKey).build();
//
//        job.getJobDataMap().put("content", "What is your opinion? John");
//
//        // Trigger the job to run now, and then repeat every 40 seconds
//        Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(
//                CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionDoNothing())
//                .build();
//
//        // Tell quartz to schedule the job using our trigger
//        scheduler.scheduleJob(job, trigger);
//
//        return ResultBean.success(jobKey + " created.");
//    }
//
//
//    @RequestMapping(value = baseuri + "/addMock")
//    public ResultBean<String> addMockedSysJob(String deploymentSetId) throws Exception {
//        AbsJob absJob = JobFactory.newJob("DeploymentSetInstallJob");
//        com.rocketsoftware.rdop.dao.rdop.model.Job job = new com.rocketsoftware.rdop.dao.rdop.model.Job();
//        absJob.setJob(job);
//        absJob.setExecutor("liujun");
//        job.setId(null);
//        job.setName("DeploymentSetInstallJob");
//        job.setJobKey("DeploymentSetInstallJob");
//        job.setDescription("This is a mocked job creation.");
//        job.setEnabled(1);
//        job.setClassName("DeploymentSetInstallJob");
//        job.setrObjectId(deploymentSetId);
//        job.setDelFlag(0);
//        job.setCategory(AbsJob.Category.DEPLOYMENT.getCode());
//        job.setThresholdEnabled(false);
//        job.setExecuteThreshold(0L);
//        job.setForceStopThreshold(0l);
//        job.setNoReactionThreshold(0l);
//        job.setStartDelayThreshold(0L);
//
//        Map<String, Object> map = Maps.newHashMap();
//        map.put("thresholdEnabled", false);
//        map.put("sendSuccessMail", false);
//        map.put("sendFailMail", false);
//        job.setProps(objectMapper.writeValueAsString(map));
//
//
//        jobService.saveJob(absJob, "liujun");
//
//        return ResultBean.success(absJob.getJob().getId() + " created.");
//    }
//
//    @RequestMapping(value = "scheduler/addMock")
//    public ResultBean<String> addSchedulerMock(String jobId) throws Exception {
//        com.rocketsoftware.rdop.dao.rdop.model.Scheduler scheduler = new com.rocketsoftware.rdop.dao.rdop.model.Scheduler();
//        Date now = new Date();
//        scheduler.setId(null);
//        scheduler.setName("DeploymentSetInstallJob Scheduler");
//        scheduler.setCategory(0L);
//        scheduler.setPriority(0);
//        scheduler.setSchedulerKey("DeploymentSetInstallJobScheduler");
//        scheduler.setDescription("This is release scheduler.");
//        scheduler.setEnabled(1);
//        scheduler.setStartDate(now);
//        scheduler.setEndDate(new GregorianCalendar(2022, Calendar.JANUARY, 1).getTime());
//        scheduler.setCronExpression("0 0/5 12 26 JUL ? 2021");
//        scheduler.setJobId(jobId);
//        scheduler.setDelFlag(0);
//
//
//        Map<String, Object> map = Maps.newHashMap();
//        map.put("statDate", now);
//        map.put("endDate", new GregorianCalendar(2022, Calendar.JANUARY, 1).getTime());
//        map.put("sendFailMail", false);
//        map.put("sendSuccessMail", false);
//        map.put("executor", "liu Jun");
//        scheduler.setProps(objectMapper.writeValueAsString(map));
//
//
//        this.schedulerService.save(scheduler, "liu jun");
//
//        return ResultBean.success(scheduler.getId() + " created.");
//    }
//
//    @RequestMapping(value = "scheduler/quartzRegister")
//    public ResultBean<String> quartzRegister(String schedulerId) throws Exception {
//        com.rocketsoftware.rdop.dao.rdop.model.Scheduler scheduler = this.schedulerService.getScheduler(schedulerId);
//        schedulerService.registQuartzScheduler(scheduler);
//
//        return ResultBean.success(scheduler.getId() + " registered.");
//    }
//
//    @RequestMapping(value = baseuri + "/enqueueMock")
//    public ResultBean<String> enqueueMock() throws Exception {
//        String jobId = "004B27E4";
//        AbsJob absJob = jobService.getJob(jobId);
//
//        List<JobQueue>  waitingAndExecutingJobs = jobQueueService.getWaitingAndExecutingJobs(Lists.newArrayList(jobId));
//        if(waitingAndExecutingJobs.isEmpty()) {
//            this.jobQueueService.enqueue("0", jobId, new Date(), "liujun");
//        }
//
//        return ResultBean.success(absJob.getJob().getId() + " enqueued.");
//    }
//
//    @RequestMapping(value = baseuri + "/batch")
//    public ResultBean<String> updateProgressAndLog() throws Exception {
//        Map<String, JobContextImpl.Progress> progressMap = Maps.newHashMap();
//        JobContextImpl ctx = new JobContextImpl();
//        JobContextImpl.Progress progress = ctx.new Progress(23l, 100l);
//        Map<String, String> logMap = Maps.newHashMap();
//        logMap.put("8552180E2C8247FC94A32FCD00FBDC4E", "8552180E2C8247FC94A32FCD00FBDC4E");
//        logMap.put("4AB2723D74384900813B1E663FC608FC", "4AB2723D74384900813B1E663FC608FC");
//        logMap.put("BA01B361E7AD412685965F750BEAD632", "BA01B361E7AD412685965F750BEAD632");
//        logMap.put("33A46BE7A14C43A28F38C4D4C706A35F", "33A46BE7A14C43A28F38C4D4C706A35F");
//        progressMap.put("8552180E2C8247FC94A32FCD00FBDC4E", progress);
//        progressMap.put("4AB2723D74384900813B1E663FC608FC", progress);
//        progressMap.put("BA01B361E7AD412685965F750BEAD632", progress);
//        progressMap.put("33A46BE7A14C43A28F38C4D4C706A35F", progress);
//        jobQueueService.updateProgressAndLog(progressMap, logMap);
//
//        return ResultBean.success("Done for updateProgressAndLog.");
//    }
}